package com.nsi.async;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.nsi.util.RedisUtils;
import com.nsi.pojo.PostCategoryItem;
import com.nsi.service.CommunityUserService;
import com.nsi.service.PostCategoryItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author Li Yan
 * @create 2019-12-24
 **/
@Component
@Slf4j
public class AutoCommentsTask {

    @Autowired
    private PostCategoryItemService postCategoryItemService;
    @Autowired
    private CommunityUserService communityUserService;

    /**
     * 30分钟自动执行
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void execute() throws Exception {
        //待审核消息通知
        EntityWrapper<PostCategoryItem> wrapper = new EntityWrapper<>();
        wrapper.eq("is_check", 0);
        int postCount = postCategoryItemService.selectCount(wrapper);
        //有待审核的帖子
        if (postCount >= 1) {
            int errCode = -1;
            int messageNum = 1;
            // Redis如果没有数据，插入初始数据，否则取出数据
            if (RedisUtils.searchRedis("sendMessage") == null) {
                log.info("redis空内容,置为 1");
                //约两小时后 失效
                RedisUtils.expireSet("sendMessage", 7000000, Integer.toString(1));
            } else {
                messageNum = Integer.valueOf(RedisUtils.searchRedis("sendMessage"));
            }

            // 判断发送消息数量 改为两小时最多5次 //发送消息  消息数加一
            if (messageNum <= 5) {
                errCode = communityUserService.SendSubscribeMessage();
                RedisUtils.alterTimeRedis("sendMessage", Integer.toString(messageNum + 1));
            } else {
                log.info("两小时内消息发送超过三次，消息发送暂停");
            }
            if (errCode > 1) {
                log.error("定时任务 发送异常：错误代码：" + errCode);
            }
        }


    }
}
